package com.tmt.im.service.config;

import io.minio.MinioClient;
import io.minio.SetBucketLifecycleArgs;
import io.minio.messages.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/11 11:08
 * @Version 1.0
 **/
@Slf4j
@Configuration
public class MinioConfig {

    // API 端点
    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * 存储桶名称
     */
    @Value("${minio.bucket}")
    private String bucket;

    // Acess Key
    @Value("${minio.access-key}")
    private String accessKey;

    // Secret Key
    @Value("${minio.secret-key}")
    private String secretKey;

    @Value("${minio.expire-days:3}")
    private int expireDays;

    @Bean
    public MinioClient minioClient() {
        MinioClient client = MinioClient.builder()
                .endpoint(this.endpoint)
                .credentials(this.accessKey, this.secretKey)
                .build();

        try {
            client.setBucketLifecycle(
                    SetBucketLifecycleArgs
                            .builder()
                            .config(new LifecycleConfiguration(
                                    List.of(
                                            new LifecycleRule(Status.ENABLED,
                                                    null,
                                                    new Expiration((ResponseDate) null, 2 * expireDays, null),
                                                    //聊天数据中的文件仅保留2倍expireDays时间。
                                                    new RuleFilter("/ChatData"),
                                                    "expiredDataDeleteRule",
                                                    null,
                                                    null,
                                                    null)
                                    )
                            ))
                            .bucket(this.bucket)
                            .build()
            );
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        return client;
    }
}
